from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import get_user_model
from .models import Conversation, Message
from .forms import MessageForm, NewConversationForm

User = get_user_model()


@login_required
def inbox(request):
    conversations = Conversation.objects.filter(
        participants=request.user
    ).prefetch_related('participants', 'messages').order_by('-updated_at')
    return render(request, 'messaging/inbox.html', {'conversations': conversations})


@login_required
def conversation_detail(request, conversation_id):
    conversation = get_object_or_404(
        Conversation.objects.filter(participants=request.user),
        pk=conversation_id
    )

    # 标记未读消息为已读
    Message.objects.filter(
        conversation=conversation,
        sender__ne=request.user,
        is_read=False
    ).update(is_read=True)

    if request.method == 'POST':
        form = MessageForm(request.POST)
        if form.is_valid():
            message = form.save(commit=False)
            message.conversation = conversation
            message.sender = request.user
            message.save()
            conversation.save()  # 更新对话时间
            return redirect('conversation_detail', conversation_id=conversation.id)
    else:
        form = MessageForm()

    return render(request, 'messaging/conversation.html', {
        'conversation': conversation,
        'form': form
    })


@login_required
def new_conversation(request):
    if request.method == 'POST':
        form = NewConversationForm(request.POST)
        if form.is_valid():
            recipient = User.objects.get(username=form.cleaned_data['recipient'])
            content = form.cleaned_data['content']

            # 创建或获取对话
            conversation = Conversation.objects.create()
            conversation.participants.add(request.user, recipient)

            # 创建初始消息
            Message.objects.create(
                conversation=conversation,
                sender=request.user,
                content=content
            )

            return redirect('conversation_detail', conversation_id=conversation.id)
    else:
        form = NewConversationForm()

    return render(request, 'messaging/new_conversation.html', {'form': form})